package lc.smart.android.net;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.os.Handler;
import android.os.Message;

public class MySocket
{
	// 120.192.187.243 9000   8999
	private static final String HOST = "120.192.187.243";// 202.85.209.80
	private static final int PORST = 9000;// 7123
	private static final int TIMEOUT = 20 * 1000;
	private static final int MAXTRIES = 1;
	private byte[] bytesToSend = new byte[6];

	/**
	 * 发送数据包
	 * */
	public void getUDPServerAndSendData(Handler mHandler)
	{
		//Log.v(TAG, "---------------------------getUDPServerAndSendData()");

		// 1. 构造UDP DatagramSocket对象
		DatagramSocket socketUDP;
		try
		{
			socketUDP = new DatagramSocket();
			// 2。指定timeout时间，防止进入无限等待状态
			socketUDP.setSoTimeout(TIMEOUT);
			// 3. 构造收发的报文对象
			DatagramPacket sendPacket = new DatagramPacket(bytesToSend,
					bytesToSend.length, InetAddress.getByName(HOST), PORST);
			DatagramPacket receivePacket = new DatagramPacket(
					new byte[bytesToSend.length], bytesToSend.length);
			// 4.指定尝试的次数
			int tries = 0;
			boolean receivedResponse = false;
			do
			{
				socketUDP.send(sendPacket);
				//				System.out.println("---------------1111:"
				//						+ Constants.bytesToSend.length);
				System.out.println("--------------以10进制打印");
				for (int i = 0; i < bytesToSend.length; i++)
				{
					//Constants.bytesToSend[13 - i] =  Constants.bytesToSend[i];
					if (i % 16 == 0) System.out.println();
					System.out.print(bytesToSend[i] + " ");

				}
				System.out.println();
				System.out.println("--------------以16进制打印");
				for (int i = 0; i < bytesToSend.length; i++)
				{
					if (i % 16 == 0) System.out.println();
					String strHex = new String();
					strHex = Integer.toHexString(bytesToSend[i]).toUpperCase();
					if (strHex.length() > 3) System.out.print(strHex
							.substring(6));
					else if (strHex.length() < 2) System.out
							.print("0" + strHex);
					else System.out.print(strHex);
					System.out.print(" ");

					//System.out.print(" " + bytesToSend[i]);

				}
				System.out.println();

				try
				{
					socketUDP.receive(receivePacket);
					System.out.println("Handling client at "
							+ receivePacket.getAddress().getHostAddress()
							+ " on port " + receivePacket.getPort());

					if (!receivePacket.getAddress().equals(
							InetAddress.getByName(HOST))) { throw new IOException(
							"Received packet from an unknown source"); }
					receivedResponse = true;
				}
				catch (InterruptedIOException e)
				{
					tries += 1;
					System.out.println("Timed out, " + (MAXTRIES - tries) + "");
				}

			} while ((!receivedResponse) && (tries < MAXTRIES));
			if (receivedResponse)
			{
				String string = new String(receivePacket.getData().toString());
				//string = Integer.valueOf(string, 16).toString();

				System.out
						.println("---------------------------------接收到的Received: "
								+ string);
				Message msg = new Message();
				msg.what = 100;
				msg.obj = string;
				mHandler.sendMessage(msg);
			}
			else
			{

				System.out.println("No response -- giving up.");
				Message msg = new Message();
				msg.what = 101;
				msg.obj = "No response";
				mHandler.sendMessage(msg);
			}
			// 5. 关闭socket
			socketUDP.close();

		}
		catch (SocketException e)
		{
			// TODO Auto-generated catch block
			Message msg = new Message();
			msg.what = 101;
			msg.obj = "网络异常";
			mHandler.sendMessage(msg);
			e.printStackTrace();
		}
		catch (UnknownHostException e)
		{
			// TODO Auto-generated catch block
			Message msg = new Message();
			msg.what = 101;
			msg.obj = "服务器维护中...";
			mHandler.sendMessage(msg);
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			Message msg = new Message();
			msg.what = 101;
			msg.obj = "发送数据包失败，请重试！";
			mHandler.sendMessage(msg);
			e.printStackTrace();
		}

	}
}
